import util from '../../utils/util.js';
const FN = require('../../utils/public');
const { configApp } = require('../../utils/config.js');
const qiniuUploader = require("../../utils/qiniuUploader");
import commonAPI from '../../api/api'
import { getNotificationInfo } from '../../api/api'
import studyTaskAPI, { reserveTaskList } from '../../api/studyTaskAPI'
import loginAPI from '../../api/loginAPI'
const app = getApp();
// 在页面中定义插屏广告
let interstitialAd = null
Page({

  /**
   * 页面的初始数据
   */
  data: {
    advertisement: [],
    notificationInfo: [],
    reserveTaskArr: [],// 预约集合
    show: false,
    showWxuserinfoUseto: false,
    wxUserInfo: {},
    showScheduled: false,// 已预约弹框
    evadingAudit: { evadingAuditHide: 'true' },
    beforeClose: null,
    miniappInfo: {},
    show4hasCancelReservation: false,
    allNoReserved: [],// 未预约数量
    actions: [
      { name: '取消预约', color: '#ee0a24' },
    ],
    loading: true,
    appointmentSet: [],//   提交数据库参数
    priTmplIdArr: [],// 小程序订阅消息
    labelArr: []// 小程序标签
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    this.getReserveTaskList();// 预约数据集
    this.getSubscribeMsg();// 订阅消息
    app.getWXuserInfo();
    app.callback4WXuserInfo = data => {
      that.setData({
        wxUserInfo: data,
      })
    }
    app.getMiniappInfo()// 小程序信息
    app.callback4MiniappInfo = miniappInfo => {
      let labelArr = miniappInfo.miniappInfoLabel ? miniappInfo.miniappInfoLabel.split(","):[];
      that.setData({
        labelArr,
        miniappInfo,
        loading: false
      })
    }
    this.getNotification();// 广告
    app.getADByminiappinfoid();
    app.callback4AD = data => {
      that.createAD(data);
    }
  },

  // 查询预约列表
  getReserveTaskList() {
    let that = this;
    reserveTaskList({ pageSize: 150, pageNum: 1 }).then(res => {
      that.setData({
        reserveTaskArr: res.data.list
      })
      that.hasAllReservedTool();
    })
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.uploadUserHeaderImg(avatarUrl)
  },

  uploadUserHeaderImg(avatarUrl) {
    var that = this, filePath = avatarUrl, fileName = "avatarUrl" + new Date().getTime() + ".png";
    this.initQiniu();
    // 向七牛云上传
    qiniuUploader.upload(filePath, (res) => {
      res.fileName = fileName;
      if (res.hasOwnProperty("error")) {
        FN.Toast('上传失败，请重新上传')
        that.initQiniu();
      } else {
        let url = "wxUserInfo.avatarUrl"
        this.setData({
          [url]: res.fileURL
        })
      }
    }, (error) => {
      console.error('error: ' + JSON.stringify(error));
    }, { key: fileName }, (progress) => {
    }, cancelTask => that.setData({ cancelTask })
    );
  },

  initQiniu: function () {
    var options = {
      region: 'ECN',
      uptokenURL: configApp.api_base_url + 'qiniu/getUploadToken',
      domain: configApp.qiniuBucketURLPrefix,
      shouldUseQiniuFileName: true
    }
    // 将七牛云相关配置初始化进本sdk
    qiniuUploader.init(options);
  },

  getUserInfo(event) {
    console.log(event);

  },

  // 取消就直接登录
  doLogin() {
    console.log('取消就直接登录')
    wx.reLaunch({
      url: '../taskList/taskList',
    })
  },

  // 进入
  login: function (e) {
    var wxUserInfo = this.data.wxUserInfo;
    this.subscribeMessage();
    wx.setClipboardData({data: 'data',success (res) {}})
    if (wxUserInfo && wxUserInfo.avatarUrl && wxUserInfo.nickName) {
      wx.reLaunch({
        url: '../taskList/taskList',
      });
    } else {
      this.setData({
        show: true,
        beforeClose: this.checkData()
      });
    }
  },

  // 公告
  getNotification() {
    var that = this;
    getNotificationInfo({}).then(res => {
      if (res.code == '200') {
        that.setData({
          notificationInfo: res.data
        })
      }
    })
  },

  // 创建广告
  createAD(advertisement) {
    var that = this, adUnitId = "";
    var pageUrl = util.getCurrentPageUrl()
    var item = advertisement.find(obj => obj.advertisementPage === pageUrl);
    adUnitId = item ? item.unitId : ""
    if (wx.createInterstitialAd && adUnitId) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId
      })
      interstitialAd.onLoad(() => { })
      interstitialAd.onError((err) => { })
      interstitialAd.onClose(() => { })
    }
    if (interstitialAd) {
      interstitialAd.show().catch((err) => {
        console.error(err)
      })
    }
  },

  // 微信用途
  showWxuserinfoUsetoTip() {
    this.setData({
      showWxuserinfoUseto: !this.data.showWxuserinfoUseto
    })
  },

  // 关闭预告弹窗
  onCloseOrOpen4Scheduled() {
    this.setData({ showScheduled: !this.data.showScheduled });
  },

  // 关闭弹窗 event.detail
  onClose(event) {
    if (event.detail == 'confirm') {

    } else {
      this.setData({
        show: false
      })
    }
  },

  // 保存用户信息
  saveWXinfo: function () {
    var that = this;
    wx.login({
      success(result) {
        if (result.code) {
          const userInfo = {
            avatarUrl: that.data.wxUserInfo.avatarUrl,
            nickName: that.data.wxUserInfo.nickName,
            code: result.code
          }
          loginAPI.codetransformationOpenId(userInfo).then(res => {
            app.globalData.wxUserInfo.avatarUrl = that.data.wxUserInfo.avatarUrl
            app.globalData.wxUserInfo.nickName = that.data.wxUserInfo.nickName// 更新全局的微信信息
            that.setData({
              show: false,
              showWxuserinfoUseto: false,
            })
          })
        }
      }
    })

  },

  // 监听昵称改变
  onChangeNickname(e) {
    let nickName = "wxUserInfo.nickName"
    this.setData({
      [nickName]: e.detail.value
    })
  },

  // 表单验证，主要验证是否为空
  checkData() {
    return (type) => {
      if (type == 'confirm') {// 点击确定 
        if (this.data.wxUserInfo.avatarUrl == "" || this.data.wxUserInfo.avatarUrl == null) {
          FN.Toast('请上传微信头像')
          return false
        } else if (this.data.wxUserInfo.nickName == "" || this.data.wxUserInfo.nickName == null) {
          FN.Toast('请输入微信昵称')
          return false
        }
        return true
      } else {// 
        return true
      }
    }

  },

  // 单个预约操作
  reservation(e) {
    this.subscribeMessage();
    const item = e.currentTarget.dataset.item;
    item.subscribeTasksStatus = '1'
    this.setData({
      appointmentSet: [item]
    })
    this.onselect4hasCancelReservation();
    setTimeout(function () {
      FN.Toast('预约成功，下发任务时，系统会消息提醒您', '', 3000)
    }, 2000)
  },

  // 取消预约,同时弹框询问确认是否取消
  cancelReservation(e) {
    const item = e.currentTarget.dataset.item;
    item.subscribeTasksStatus = '0'
    this.setData({
      show4hasCancelReservation: true,
      appointmentSet: [item]
    })
  },

  // 隐藏预约弹框
  onClose4hasCancelReservation(e) {
    this.setData({
      show4hasCancelReservation: false,
    })
  },

  // 调用接口预约|取消预约
  onselect4hasCancelReservation(e) {
    let that = this;
    studyTaskAPI.batchSubscribe({ list: this.data.appointmentSet }).then(res => {
      that.getReserveTaskList();// 刷新页面，可不调接口刷新，后期优化
      that.onClose4hasCancelReservation();
    })
  },

  // 计算方法：是否已全部预约
  hasAllReservedTool() {
    const arr = this.data.reserveTaskArr;
    let tmpArr = arr.filter(res => res.subscribeTasksStatus == '0' || res.subscribeTasksStatus == null)
    this.setData({
      allNoReserved: tmpArr
    })
  },

  // 订阅当前所有任务:将所有为订阅数据全部赋值给appointmentSet
  subscribeAllTasks() {
    this.subscribeMessage();
    const allNoReservedList = this.data.allNoReserved;
    allNoReservedList.map(item => {
      item.subscribeTasksStatus = "1"
    })
    this.setData({
      appointmentSet: allNoReservedList
    })
    this.onselect4hasCancelReservation();
    setTimeout(function () {
      FN.Toast('预约成功，下发任务时，系统会消息提醒您', '', 3000)
    }, 2000)
  },

  // 订阅当前所有任务:将所有为订阅数据全部赋值给appointmentSet
  unsubscribeAllTasks() {
    const subscribedList = this.data.reserveTaskArr.filter(res => res.subscribeTasksStatus == '1')
    subscribedList.map(item => {
      item.subscribeTasksStatus = "0"
    })
    this.setData({
      appointmentSet: subscribedList
    })
    this.onselect4hasCancelReservation();
  },

  // 获取订阅消息
  getSubscribeMsg: function () {
    var that = this;
    commonAPI.getSubscribeMsg({ pageUrl: util.getCurrentPageUrl() }).then(res => {
      if (res.code == '200' && res.data.length > 0) {
        var arr = res.data[0].priTmplIdArr.split(",")
        that.setData({
          priTmplIdArr: arr
        })
      }
    })
  },

  subscribeMessage() {
    var that = this;
    wx.requestSubscribeMessage({
      tmplIds: that.data.priTmplIdArr,
      success(res) {

      }
    })

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})